package com.nb.protocol.db;

import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
import com.nb.protocol.protocol.MessageHolder;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @function:
 * @author: hjw
 * @date: 2018/1/7
 * @company: Sinoregal
 * @copyright: 2018 www.sinoregal.cn. All rights reserved.
 */
public class GpsDao {
    private static final Logger logger = Logger.getLogger(GpsDao.class);

    public static void reportData(MessageHolder messageHolder) throws SQLException {
        String sql = "INSERT INTO sensor_gps (sn,create_date,status,lon,lat,speed) VALUES (?,?,?,?,?,?) ";

        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = DbCtrl.getConnection();
            connection.setAutoCommit(false);
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, messageHolder.getCpuId());
            pstmt.setTimestamp(2, new Timestamp(new Date().getTime()));
            pstmt.setInt(3, messageHolder.getBody()[0]);

            pstmt.setFloat(4, bytesToFloat(messageHolder.getBody(), 1));
            pstmt.setFloat(5, bytesToFloat(messageHolder.getBody(), 5));
            pstmt.setInt(6, bytesToShort(messageHolder.getBody(), 9));

            pstmt.executeUpdate();
            connection.commit();

            //connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            logger.error("写入传感器数据出现错误:" + e.getMessage());
            throw new SQLException(e);
        } finally {
            try {
                connection.setAutoCommit(true);
                DbCtrl.close(connection, pstmt);
            } catch (SQLException e) {
            }
        }

    }

    public static int bytesToInt(byte[] ary, int offset) {
        int value;
        value = (int) ((ary[offset] & 0xFF)
                | ((ary[offset + 1] << 8) & 0xFF00)
                | ((ary[offset + 2] << 16) & 0xFF0000)
                | ((ary[offset + 3] << 24) & 0xFF000000));
        return value;
    }

    public static float bytesToFloat(byte[] ary, int offset) {
        byte[] bytes = new byte[]{ary[offset],ary[offset + 1],ary[offset + 2],ary[offset + 3]};
        int temp = Integer.parseInt(byteArray2HexString(bytes),16);

        return (new BigDecimal(temp).divide(new BigDecimal(1000000))).floatValue();
    }

    public static String byteArray2HexString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        //先把byte[] 转换维char[]，再把char[]转换为字符串
        char[] chars = new char[bytes.length * 2]; // 每个byte对应两个字符
        final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        for (int i = 0, j = 0; i < bytes.length; i++) {
            chars[j++] = hexDigits[bytes[i] >> 4 & 0x0f]; // 先存byte的高4位
            chars[j++] = hexDigits[bytes[i] & 0x0f]; // 再存byte的低4位
        }

        return new String(chars);
    }

    public static int bytesToShort(byte[] ary, int offset) {
        //return (short) ((0xff & (ary[offset]) | (0xff00 & ((ary[offset + 1] << 8)))));
        byte[] bytes = new byte[]{ary[offset],ary[offset + 1]};
        return Integer.parseInt(byteArray2HexString(bytes),16);
    }
}
